<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Controller\AdminController;

class UpyunController extends AdminController {
	
	public $upyun_domain;
	public $site_url;
	public function _initialize() {
		parent::_initialize();
		\Think\Log::write("upyun initialize");
		//$this->upyun_domain=UNYUN_DOMAIN;
		//$this->assign('upyun_domain','http://'.$this->upyun_domain);

		$this->siteUrl=C('site_url');
	}
	public function upload(){
		if (!function_exists('imagecreate')){
			exit('php不支持gd库，请配置后再使用');
		}
		if (IS_POST){
			$cate = I('cate');
			
			$return=$this->localUpload('',$cate);
			// 对回传的msg中的url链接进行替换,适配3.2
			$str1 = str_replace('http:', 'ptth', $return['msg']);
			$str2 = str_replace('/', 'xgxg', $str1);
			
			$urlhref =  '<script>location.href="http://' .$_SERVER['HTTP_HOST']. U("Admin/Upyun/upload", array('msg'=>$str2, 'error'=>$return['error']), false) .'";</script>';
			\Think\Log::write("urlhref => " . $urlhref);
			echo $urlhref;
		}else {
			$this->assign('cate', I('cate'));
			$this->display('local');
		}
	}
	
	public function uploadReturn(){
		$handled=0;
		$form_api_secret = $this->form_api_secret; /// 表单 API 功能的密匙（请访问又拍云管理后台的空间管理页面获取）
		if(!isset($_GET['code']) || !isset($_GET['message']) || !isset($_GET['url']) || !isset($_GET['time'])){
			header('HTTP/1.1 403 Not Access');
			die('非法操作哦');
		}
		if(isset($_GET['sign'])){ /// 正常签名
			if(md5("{$_GET['code']}&{$_GET['message']}&{$_GET['url']}&{$_GET['time']}&".$form_api_secret) == $_GET['sign']){
				/// 合法的上传回调
				if($_GET['code'] == '200'){
					/// 上传成功
					$handled=1;
					//
					$fileUrl='http://'.$this->upyun_domain.$_GET['url'];

					$fileinfo=get_headers($fileUrl,1);
					$fileinfo['Content-Type']=$fileinfo['Content-Type']?$fileinfo['Content-Type']:'';
					M('Users')->where(array('id'=>$this->user['id']))->setInc('attachmentsize',intval($fileinfo['Content-Length']));
					M('Files')->add(array('token'=>$this->token,'size'=>intval($fileinfo['Content-Length']),'time'=>time(),'type'=>$fileinfo['Content-Type'],'url'=>$fileUrl));
					if($this->_get('imgfrom') == 'photo_list'){
						echo $fileUrl;exit;
					}
				}else{
					$handled=1;
					/// 上传失败
				}
			}else{
				/// 回调的签名错误
				header('HTTP/1.1 403 Not Access');
				die('回调的签名错误,请检查总后台上传配置信息');
			}
		}elseif(isset($_GET['non-sign'])){ /// 缺少操作员密码的签名
			if(md5("{$_GET['code']}&{$_GET['message']}&{$_GET['url']}&{$_GET['time']}&") == $_GET['non-sign']){
				/// 合法的上传回调
				$handled=1;
				/// 上传失败
			}else{
				/// 回调的签名错误
				header('HTTP/1.1 403 Not Access');
				die('回调的签名错误,请检查总后台上传配置信息。。。');
			}
		}else{
			header('HTTP/1.1 403 Not Access');
			die('回调的签名错误,请检查总后台上传配置信息...');
		}
		$this->assign('result',1);
		if ($handled){
			$status=$this->_status($_GET['code'],$_GET['message']);
			$this->assign('error',$status['error']);
			$this->assign('message',$status['msg']);
			$this->display('upload');
		}
	}
	public function editorUploadReturn(){
		$handled=0;
		$form_api_secret = $this->form_api_secret; /// 表单 API 功能的密匙（请访问又拍云管理后台的空间管理页面获取）
		if(!isset($_GET['code']) || !isset($_GET['message']) || !isset($_GET['url']) || !isset($_GET['time'])){
			header('HTTP/1.1 403 Not Access');
			die();
		}
		if(isset($_GET['sign'])){ /// 正常签名
			if(md5("{$_GET['code']}&{$_GET['message']}&{$_GET['url']}&{$_GET['time']}&".$form_api_secret) == $_GET['sign']){
				/// 合法的上传回调
				if($_GET['code'] == '200'){
					$fileUrl=$status['msg'];
					$fileinfo=get_headers($fileUrl,1);
					M('Users')->where(array('id'=>$this->user['id']))->setInc('attachmentsize',intval($fileinfo['Content-Length']));
					M('Files')->add(array('token'=>$this->token,'size'=>intval($fileinfo['Content-Length']),'time'=>time(),'type'=>$fileinfo['Content-Type'],'url'=>$fileUrl));
					/// 上传成功
					$handled=1;
				}else{
					$handled=1;
					/// 上传失败
				}
			}else{
				/// 回调的签名错误
				header('HTTP/1.1 403 Not Access');
				die();
			}
		}elseif(isset($_GET['non-sign'])){ /// 缺少操作员密码的签名
			if(md5("{$_GET['code']}&{$_GET['message']}&{$_GET['url']}&{$_GET['time']}&") == $_GET['non-sign']){
				/// 合法的上传回调
				$handled=1;
				/// 上传失败
			}else{
				/// 回调的签名错误
				header('HTTP/1.1 403 Not Access');
				die();
			}
		}else{
			header('HTTP/1.1 403 Not Access');
			die();
		}
		//$this->assign('result',1);
		if ($handled){
			$status=$this->_status($_GET['code'],$_GET['message']);
			echo json_encode(array('error' => $status['error'], 'message' => $status['msg']));
		}else {
			echo json_encode(array('error' => 1, 'message' =>'未知错误'));
		}
	}
	function _status($code,$message){
		switch ($_GET['code']){
			default:
				$error=1;
				break;
			case 200:
				$error=0;
				break;
		}
		switch ($_GET['message']){
			default:
				return array('error'=>1,'msg'=>$message);
				break;
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case '':
				break;'';
			case 200:
				return array('error'=>0,'msg'=>'文件上传成功');
				break;
		}
		return array('error'=>0,'msg'=>$message);
	}
	function deleteFile(){
		$upyun = new UpYun($this->bucket, 'user', 'pwd');
		$upyun->deleteFile($filePath);
	}
	function editorUpload(){
		echo $json->encode(array('error' => 1, 'message' => $msg));
	}
	function kindedtiropic(){
		if ($this->upload_type=='upyun'){
			$upyun_pic = new UpYun(UNYUN_BUCKET, UNYUN_USERNAME, UNYUN_PASSWORD, $api_access[0]);
			try{
				$api_access = array(UpYun::ED_AUTO, UpYun::ED_TELECOM, UpYun::ED_CNC, UpYun::ED_CTT);
				//$php_path = dirname(__FILE__) . '/';
				//$php_url = dirname($_SERVER['PHP_SELF']) . '/';

				//文件保存目录路径
				//$save_path = $php_path . '../attached/';


				//文件保存目录URL
				//$save_url = $php_url . '../attached/';

				//$domain_file = $_config['file']['domain'];
				$domain_pic = 'http://'.UNYUN_DOMAIN;
				//$dir_file = $_config['file']['dir'];
				$dir_pic = '/'.$this->token.'/';
				$save_path = '';
				$save_url = '';

				//定义允许上传的文件扩展名
				$ext_arr = array(
				'image' => explode(',',C('up_exts')),
				'flash' => array('swf', 'flv'),
				'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
				'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
				);
				//最大文件大小
				$max_size = intval(C('up_size'))*1000;

				//$save_path = realpath($save_path) . '/';

				//PHP上传失败
				if (!empty($_FILES['imgFile']['error'])) {
					switch($_FILES['imgFile']['error']){
						case '1':
							$error = '超过php.ini允许的大小。';
							break;
						case '2':
							$error = '超过表单允许的大小。';
							break;
						case '3':
							$error = '图片只有部分被上传。';
							break;
						case '4':
							$error = '请选择图片。';
							break;
						case '6':
							$error = '找不到临时目录。';
							break;
						case '7':
							$error = '写文件到硬盘出错。';
							break;
						case '8':
							$error = 'File upload stopped by extension。';
							break;
						case '999':
						default:
							$error = '未知错误。';
					}
					$this->alert($error);
				}

				//有上传文件时
				if (empty($_FILES) === false) {
					//原文件名
					$file_name = $_FILES['imgFile']['name'];
					//服务器上临时文件名
					$tmp_name = $_FILES['imgFile']['tmp_name'];
					//文件大小
					$file_size = $_FILES['imgFile']['size'];
					//检查文件名
					if (!$file_name) {
						$this->alert("请选择文件。");
					}
					//检查目录
					//if (@is_dir($save_path) === false) {
					// alert("上传目录不存在。");
					//}
					//检查目录写权限
					//if (@is_writable($save_path) === false) {
					// alert("上传目录没有写权限。");
					//}
					//检查是否已上传
					if (@is_uploaded_file($tmp_name) === false) {
						$this->alert("上传失败。");
					}
					//检查文件大小
					if ($file_size > $max_size) {
						$this->alert("上传文件大小超过限制。");
					}
					//检查目录名
					$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
					if (empty($ext_arr[$dir_name])) {
						$this->alert("目录名不正确。");
					}
					//获得文件扩展名
					$temp_arr = explode(".", $file_name);
					$file_ext = array_pop($temp_arr);
					$file_ext = trim($file_ext);
					$file_ext = strtolower($file_ext);
					//检查扩展名
					if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
						$this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
					}
					//创建文件夹
					if ($dir_name !== '') {
						$save_path .= $dir_name . "/";
						$save_url .= $dir_name . "/";

						//if (!file_exists($save_path)) {
						// mkdir($save_path);
						//}
					}
					$ymd = date("Ymd");
					$save_path .= $ymd . "/";
					$save_url .= $ymd . "/";

					//if (!file_exists($save_path)) {
					// mkdir($save_path);
					//}

					//新文件名
					$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
					//移动文件
					$file_path = $save_path . $new_file_name;
					$fh = fopen($tmp_name, 'r');
					$upyun_pic->writeFile($dir_pic . $file_path, $fh, True);
					$save_url = $domain_pic . $dir_pic . $save_url;
					fclose($fh);

					//if (move_uploaded_file($tmp_name, $file_path) === false) {
					// alert("上传文件失败。");
					//}
					//@chmod($file_path, 0644);
					$file_url = $save_url . $new_file_name;

					header('Content-type: text/html; charset=UTF-8');
					echo json_encode(array('error' => 0, 'url' => $file_url));
					exit;
				}else{
					$this->alert('您就先别试这里了，我们服务器禁止写入文件了，O(∩_∩)O');
				}
			}catch(Exception $e) {
				$this->alert($e->getCode().':'.$e->getMessage());
			}
		}elseif ($this->upload_type=='local'){
			$return=$this->localUpload();
			if ($return['error']){
				$this->alert($return['msg']);
			}else {
				header('Content-type: text/html; charset=UTF-8');
				echo json_encode(array('error' => 0, 'url' => $return['msg']));
				exit;
			}
		}
	}
	function localUpload($filetypes='',$cate=''){
		$upload = new \Org\Util\UploadFile();
		$upload->maxSize  = 2048*1024 ;
		if (!$filetypes){
			$upload->allowExts  = explode(',','jpeg,jpg,png,mp3,mp4,gif,cer,pem');
		}else {
			$upload->allowExts  = $filetypes;
		}
		$upload->autoSub=1;
		if (isset($_POST['width'])&&intval($_POST['width'])){
			$upload->thumb = true;
			$upload->thumbMaxWidth=$_POST['width'];
			$upload->thumbMaxHeight=$_POST['height'];
			//$upload->thumbPrefix='';
			$thumb=1;
		}
		$upload->thumbRemoveOrigin=true;
		
		//$firstLetter=substr($this->token,0,1);
		$firstLetter = empty($cate) ? '':$cate.'/';
		
		$upload->savePath =  './Public/uploads/'.$firstLetter;// 设置附件上传目录
		//
		if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public/uploads')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public/uploads')){
			mkdir($_SERVER['DOCUMENT_ROOT'].'/Public/uploads',0777);
		}
		$firstLetterDir=$_SERVER['DOCUMENT_ROOT'].'/Public/uploads/'.$firstLetter;
		if (!file_exists($firstLetterDir)||!is_dir($firstLetterDir)){
			mkdir($firstLetterDir,0777);
		}
		if (!file_exists($firstLetterDir.'/'.$this->token)||!is_dir($firstLetterDir.'/'.$this->token)){
			mkdir($firstLetterDir.'/'.$this->token,0777);
		}
		//
		$upload->hashLevel=4;
		$result = $upload->upload();
		if(!$result) {// 上传错误提示错误信息
			$error=1;
			$msg=$upload->getErrorMsg();
		}else{// 上传成功 获取上传文件信息
			$error=0;
			$info =  $upload->getUploadFileInfo();
			$this->siteUrl=$this->siteUrl?$this->siteUrl:C('site_url');
			if ($thumb==1){
				$paths=explode('/',$info[0]['savename']);
				$fileName=$paths[count($paths)-1];
				$msg=$this->siteUrl.'/'.C('MODULE_NAME').substr($upload->savePath,1).str_replace($fileName,'thumb_'.$fileName,$info[0]['savename']);
			}else {
				$msg=$this->siteUrl.'/'.C('MODULE_NAME').substr($upload->savePath,1).$info[0]['savename'];
			}
			//M('Users')->where(array('id'=>$this->user['id']))->setInc('attachmentsize',intval($info[0]['size']));
			//M('Files')->add(array('token'=>$this->token,'size'=>intval($info[0]['size']),'time'=>time(),'type'=>$info[0]['extension'],'url'=>$msg));
		}
		
		if($this->__get('imgfrom') == 'photo_list'){
			echo $msg;exit;
		}else{
			\Think\Log::write("msg => " . $msg);
			// 对于返回的图片路径进行包装，适配3.2
			//return array('error'=>$error,'msg'=>'http://'.$_SERVER['HTTP_HOST'].'/'.C('MODULE_NAME').$msg);
			return array('error'=>$error,'msg'=> $msg);
		}
		
	}
	function alert($msg) {
		header('Content-type: text/html; charset=UTF-8');
		//$json = new Services_JSON();
		echo json_encode(array('error' => 1, 'message' => $msg));
		exit;
	}
}
?>